﻿namespace Digitalmes.Application.Mes;

/// <summary>
/// 生产报表
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
[AllowAnonymous]
public sealed class ReportProductionService : IDynamicWebApiService
{
    private readonly SugarRepository<ProdTransSn> _tranSnRepo;
    private readonly SugarRepository<ReworkDoc> _reworkDocRepo;

    public ReportProductionService(SugarRepository<ProdTransSn> tranSnRepo, SugarRepository<ReworkDoc> reworkDocRepo)
    {
        _tranSnRepo = tranSnRepo;
        _reworkDocRepo = reworkDocRepo;
    }

    /// <summary>
    /// 生产统计
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<object> GetStatAsync()
    {
        // 今天完工数
        // 昨天完工数
        // 本月累计完工数
        // 本月累计返工数

        var today = DateTime.Today;
        var yesterday = today.AddDays(-1);
        var thisMonth = new DateTime(today.Year, today.Month, 1, 0, 0, 0);

        // 线上完工下线数据
        var query = await _tranSnRepo.AsQueryable()
            .Where(s => s.OfflineTime >= thisMonth && s.CurRoutingId > 0 && s.IsCompelted)
            .Select(x => new
            {
                todayCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.OfflineTime >= today, 1, 0)),
                yesterdayCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.OfflineTime >= yesterday && x.OfflineTime < today, 1, 0)),
                thisMonthCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.OfflineTime >= thisMonth, 1, 0)),
            })
            .FirstAsync();

        // 已返工数
        var thisMonthReworkCount = await _reworkDocRepo.AsQueryable()
            .Where(s => s.CompletedTime >= thisMonth)
            .CountAsync();

        return new 
        {
            query.todayCount,
            query.yesterdayCount,
            query.thisMonthCount,
            thisMonthReworkCount,
        };
    }
}
